package ComNet;

import java.io.*;
import java.net.*;

import javax.swing.JOptionPane.*;

import javax.swing.JOptionPane;
class TCPClient {
	public static void main(String argv[]) throws Exception
	{
		
		String response;
		String webPage = new JOptionPane().showInputDialog("What website?");
		Socket clientSocket = new Socket(webPage, 80);
		String message = "GET / HTTP/1.0\r\n" +
				"\r\n";
		
		
		DataOutputStream outToServer =
		new DataOutputStream(clientSocket.getOutputStream());
		
		BufferedReader inFromServer =
			new BufferedReader(new
			InputStreamReader(clientSocket.getInputStream()));

			outToServer.writeBytes(message);
			System.out.println("Message:\n\n"+message);
			while(!inFromServer.ready()){
				//Sleep
			}
			System.out.println("FROM SERVER:\n");
			
			StringBuilder sb = new StringBuilder();
			while(inFromServer.ready()){
				sb.append(inFromServer.readLine());
				sb.append('\n');
			}
			response = sb.toString();
			System.out.println(response);
			if(response.contains("200 OK")){
				if(response.contains("Content-Length")){
					System.out.println(response.substring(response.indexOf("Content-Length"), 
						response.indexOf('\n', response.indexOf("Content-Length"))));
				} else {
					System.out.println("Response message did not specify the length of the content");
				}
			} else {
				System.out.println(response.substring(0, response.indexOf('\n', 0)));
			}

			clientSocket.close();
	}

}